package com.hhf.rpc.core.protocol;


import com.hhf.rpc.core.enums.ProtocolMessageSerializerEnum;
import com.hhf.rpc.core.serializer.Serializer;
import com.hhf.rpc.core.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @Author hhf
 * @Date 2024/10/19
 * @Description 编码器
 */
@Slf4j
public class ProtocolMessageEncoder {


    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        //1.判断参数是否为空
        if (protocolMessage == null || protocolMessage.getHeader() == null){
            return Buffer.buffer();
        }
        //2.从protocolMessage中获取值
        byte magic = protocolMessage.getHeader().getMagic();
        byte version = protocolMessage.getHeader().getVersion();
        byte serializer = protocolMessage.getHeader().getSerializer();
        byte status = protocolMessage.getHeader().getStatus();
        byte type = protocolMessage.getHeader().getType();
        long requestId = protocolMessage.getHeader().getRequestId();
        //3.构建buffer
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(magic);
        buffer.appendByte(version);
        buffer.appendByte(serializer);
        buffer.appendByte(status);
        buffer.appendByte(type);
        buffer.appendLong(requestId);
        //4.获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getSerializerByKey(serializer);
        if (serializerEnum == null){
            log.error("序列化器:{}不存在",serializerEnum.toString());
        }
        //5.将消息头序列化并写入buffer
        Object body = protocolMessage.getBody();
        Serializer serializerInstance = SerializerFactory.getSerializerInstance(serializerEnum.getValue());
        byte[] bodyBytes = serializerInstance.serialize(body);
        buffer.appendInt(bodyBytes.length);
        buffer.appendBytes(bodyBytes);
        //4.返回
        return buffer;
    }
}
